import { Tooltip } from 'antd';
import pageStyles from '@/common/pageLayout.less';
import { TagSelectNew as TagSelect } from '@/components/TagSelectNew';
import { getColorTextLoadMap, getTenantID } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import MyIcon from '@/components/MyIcon';

// <<<==========================采购实施状态===========================>>>START

/**`1000`待编制*/
export const DBZ_STATE = () => `${getTenantID()}${ILoadMapTypeAll?.CURRYOUT_STATE}1000`;
/**`1000`文件编制中*/
export const WJBZZ_STATE = () => `${getTenantID()}${ILoadMapTypeAll?.CURRYOUT_STATE}1001`;
/**`1010`待实施*/
export const BZWC_STATE = () => `${getTenantID()}${ILoadMapTypeAll?.CURRYOUT_STATE}1010`;
/**`1004`澄清中*/
export const CQXG_STATE = () => `${getTenantID()}${ILoadMapTypeAll?.CURRYOUT_STATE}1004`;
/**`1006`待开标*/
export const LRKPB_STATE = () => `${getTenantID()}${ILoadMapTypeAll?.CURRYOUT_STATE}1006`;
/**`1008`采购方式变更中*/
export const CGFSBG_STATE = () => `${getTenantID()}${ILoadMapTypeAll?.CURRYOUT_STATE}1008`;
/**`1007`已开标*/
export const DB_STATE = () => `${getTenantID()}${ILoadMapTypeAll?.CURRYOUT_STATE}1007`;
/**`1014`已定标*/
export const YDB_STATE = () => `${getTenantID()}${ILoadMapTypeAll?.CURRYOUT_STATE}1014`;
/**`1012`流标*/
export const LB_STATE = () => `${getTenantID()}${ILoadMapTypeAll?.CURRYOUT_STATE}1012`;
/**`1005`待完成*/
export const DWC_STATE = () => `${getTenantID()}${ILoadMapTypeAll?.CURRYOUT_STATE}1005`;

//================================作废的状态=============================
/**`1003`招标公告【已作废】*/
export const ZBGG_STATE = () => `${getTenantID()}${ILoadMapTypeAll?.CURRYOUT_STATE}1003`;
/**`1005`投标统筹【已作废】*/
export const TBTC_STATE = () => `${getTenantID()}${ILoadMapTypeAll?.CURRYOUT_STATE}1005`;
/**`1009`废标【已作废】*/
export const FB_STATE = () => `${getTenantID()}${ILoadMapTypeAll?.CURRYOUT_STATE}1009`;
/**`1000`编制校准【已作废】*/
export const BZJZ_STATE = () => `${getTenantID()}${ILoadMapTypeAll?.CURRYOUT_STATE}1002`;
// <<<==========================采购实施状态===========================>>>END

// <<<==========================审核状态===========================>>>START
/**`1000` 审核中*/
export const SHZ_CHECKSTATE = () => `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1000`;
/**`1001` 编制中*/
export const BZZ_CHECKSTATE = () => `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1001`;
/**`1002` 审核通过*/
export const SHTG_CHECKSTATE = () => `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1002`;
/**`1003` 审核退回*/
export const SHTH_CHECKSTATE = () => `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1003`;
/**`1004` 放弃审核*/
export const FQSH_CHECKSTATE = () => `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1004`;
/**`1005` 审核作废*/
export const SHZF_CHECKSTATE = () => `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1005`;
// <<<==========================审核状态===========================>>>END

// <<<==========================采购方式变更===========================>>>START
/**`起草`*/
export const FSBG_STATE_QC = () => {
  return `${getTenantID()}${ILoadMapTypeAll?.PURCHASE_CHANGEWAY}1000`;
};
/**`审核中`*/
export const FSBG_STATE_SHZ = () => {
  return `${getTenantID()}${ILoadMapTypeAll?.PURCHASE_CHANGEWAY}1001`;
};
/**`成功`*/
export const FSBG_STATE_CG = () => {
  return `${getTenantID()}${ILoadMapTypeAll?.PURCHASE_CHANGEWAY}1002`;
};
/**`作废`*/
export const FSBG_STATE_ZF = () => {
  return `${getTenantID()}${ILoadMapTypeAll?.PURCHASE_CHANGEWAY}1003`;
};
/** 业务Controller【controller】*/
export const BGrequestController = () => {
  return 'purchaseSourceChangeController';
};
/** 流程相关&流程类别【category】*/
export const BGflowBusinessType = () => {
  return `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1002`;
};
/** 工单类型【orderType】 */
export const BGorderType = () => {
  return `${getTenantID()}${ILoadMapTypeAll.ALLORDER_TYPE}1013`;
};
/** 业务流程类别【businessCategory】【CHANGEPURCHASE_METHOD】 */
export const BGbusinessCategory = () => {
  return `${getTenantID()}${ILoadMapTypeAll.CHANGEPURCHASE_METHOD}1000`;
};
// <<<==========================采购方式变更===========================>>>END

export const stateOfRendering = (state: number | null | undefined, isShowIcon: boolean = true) => {
  if (typeof state !== 'number') return '--';
  if (state == 0) {
    return (
      <div style={{ fontSize: 15, fontWeight: 600 }}>
        {isShowIcon && <MyIcon type="icon-dian" style={{ color: '#6812f2' }} />}&nbsp;
        <span>起草</span>
      </div>
    );
  } else if (state == 1) {
    return (
      <div>
        {isShowIcon && <MyIcon type="icon-dian" style={{ color: '#2390fd' }} />}&nbsp;
        <span>审核中</span>
      </div>
    );
  } else if (state == 2) {
    return (
      <div>
        {isShowIcon && <MyIcon type="icon-dian" style={{ color: '#59d6a5' }} />}&nbsp;
        <span>审核通过</span>
      </div>
    );
  } else {
    return (
      <div>
        {isShowIcon && <MyIcon type="icon-dian" style={{ color: '#5c6f91' }} />}&nbsp;
        <span>作废</span>
      </div>
    );
  }
};

/** 拆分数据 */
export const splitExpertData = (data, type) => {
  if (!data?.length || !data) return [];
  return data?.filter((item) => item.sourceType == type);
};

/**`1000`澄清业务流程类别*/
export const BUSINESS_TYPE = () => `${getTenantID()}${ILoadMapTypeAll.CLARIFY_BUSINESSTYPE}1000`;

/** 生成随机流水单号 */
export function generateRandomNumber(type = 'SOURCE_') {
  const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  let number = '';
  for (let i = 0; i < 4; i++) {
    number += letters.charAt(Math.floor(Math.random() * letters.length));
  }
  return type + number + Math.floor(Math.random() * 1000000000);
}

/** 10位随机数 */
export const getNum_ten = () => {
  const numbers = Array.from({ length: 10 }, (_, index) => index); // 创建包含0到9的数组
  for (let i = numbers.length - 1; i > 0; i--) {
    // 随机打乱数组
    const j = Math.floor(Math.random() * (i + 1));
    [numbers[i], numbers[j]] = [numbers[j], numbers[i]];
  }
  const uniqueRandomNumber = numbers.slice(0, 10).join(''); // 取前10个元素并拼接成字符串
  return uniqueRandomNumber;
};

/** 过滤value相同的值 */
export function filterDuplicate(arr: any) {
  let result: any = [];
  for (let i = 0; i < arr.length; i++) {
    if (!result.some((item: Record<string, any>) => item.value === arr[i].value)) {
      result?.push(arr[i]);
    }
  }
  return result;
}

/** 判断值是否有两位小数点，没有则自动补零 */
export const formatDecimal = (val: any) => {
  // 不存在的话就返回'--'
  if (!val) return '0.00';
  // 将输入值转为数字，以确保处理的是数值类型
  const num = Number(val);
  // 如果转换后的数值是NaN，则直接返回原始值
  if (isNaN(num)) return '0.00';
  // 使用toFixed方法确保小数点后有两位，然后再转回字符串
  return num.toFixed(2) + '';
};

/** 将集合中的采购类型去重之后返回 */
export const returnPurchaseTypeList = ({ list, fields }) => {
  let result: any[] = [];
  list?.forEach((item) => {
    const { colorText } = getColorTextLoadMap(item?.[fields + 'Name']);
    result?.push({ value: item?.[fields], label: colorText });
  });
  result = filterDuplicate(result);
  return result;
};

/** columns内容渲染的方法【非字典】 */
export const ColumnsRenderFun = ({ isTooltip = true, text, textStyle = {}, event = undefined, record = {} }: Record<string, any>) => {
  return (
    <>
      <Tooltip title={isTooltip ? text : undefined}>
        <span className={pageStyles['over-flow-hidden']} onClick={event ? () => event(record) : undefined} style={textStyle}>
          {text == null || text == undefined || text == '' ? '--' : text}
        </span>
      </Tooltip>
    </>
  );
};

/** columns内容渲染的方法【字典】 */
export const DictionaryRenderFun = ({ isTooltip = false, text, textStyle = {}, event = undefined, record = {} }: Record<string, any>) => {
  const { colorText, color } = getColorTextLoadMap(text);
  return (
    <>
      <Tooltip title={isTooltip ? text : undefined}>
        <span className={pageStyles['over-flow-hidden']} onClick={event ? () => event(record) : undefined} style={{ color, ...textStyle }}>
          {colorText == null || colorText == undefined || colorText == '' ? '--' : colorText}
        </span>
      </Tooltip>
    </>
  );
};

/**
 * @param label 表单label
 * @param name 表单field
 * @param required 是否必填
 * @param value 单选值
 * @returns
 */
export const TagSelectRender = (label: string, name: string, required: boolean = false, value: number = 0) => {
  return (
    <TagSelect
      colSpan={12}
      formLabel={label}
      formRequired={required}
      formName={name}
      defalultKeys={isNaN(value) ? value : 0}
      radioList={[
        {
          value: 1,
          name: '是',
        },
        {
          value: 0,
          name: '否',
        },
      ]}
    />
  );
};

/**
 * setTableRowClassName 设置表格单双行类名
 */
export const setTableRowClassName = (_: Record<string, any>, index: number) => {
  return index % 2 == 0 ? 'double-row' : 'default-row';
};
/**
 * @renderOverflowText
 * @description 处理文字溢出
 * @param text 值
 * @param isShowTooltip 是否溢出隐藏并且加Tooltip
 * @returns
 */
export const renderOverflowText = (text: string | number | null, isShowTooltip = false) => {
  const index = ['0', '1'].indexOf(String(text) || '');
  const info = {
    word: text ?? '--',
    color: '',
  };

  if (index != -1) {
    info.word = index == 1 ? '是' : '否';
    info.color = index == 1 ? '#409eff' : 'red';
  }
  if (isShowTooltip && info.word != '--') {
    return (
      <Tooltip title={info.word}>
        <span className={pageStyles['over-flow-hidden']} style={{ color: info.color }}>
          {info.word}
        </span>
      </Tooltip>
    );
  } else {
    return <span style={{ color: info.color }}>{info.word}</span>;
  }
};

export const InceptionData = () => {
  return {
    mId: getNum_ten(),
    fullName: null,
    complexFlag: 0,
    complexNames: null,
    sumInTax: null,
    techScore: null,
    busiScore: null,
    priceScore: null,
    sumScore: null,
    bidFileURL: null,
    selectFlag: 0,
  };
};

export const returnDelIds = ({ oldData, newData, screen, back }) => {
  let delIds: any[] = [];
  const allids = newData?.map((i: Record<string, any>) => i?.[screen]);
  oldData?.forEach((item: Record<string, any>) => {
    if (!allids?.includes(item?.[screen])) {
      delIds?.push(item?.[back]);
    }
  });

  return delIds?.join(',') || null;
};

/**
 * 排序
 * */
export const getSorter = (prev: Record<string, any>, next: Record<string, any>): number => (prev > next ? 1 : -1);
